package pub.rookie.filing;

import java.io.File;
import java.util.LinkedList;
import java.util.Stack;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class FilingAdapter extends BaseAdapter
{
	public FilingAdapter(Context ctx, String pattern)
	{
		this.ctx = ctx;
		this.patternMatcher = new PatternMatcher(pattern);
		new AllFiles().traverse("/mnt/sdcard");
	}
	
	@Override
	public int getCount()
	{
		return queue.size();
	}

	@Override
	public Object getItem(int pos)
	{
		return queue.get(pos);
	}

	@Override
	public long getItemId(int pos)
	{
		return pos;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		if (convertView == null)
		{
			convertView = LayoutInflater.from(ctx).inflate(R.layout.item, null);
		}
		((TextView)convertView.findViewById(R.id.textView)).setText(queue.get(position).getAbsolutePath());
		
		return convertView;
	}

	private LinkedList<File> queue = new LinkedList<File>();
	
	private Handler h = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			while (!queue.isEmpty())
			{
				File file = queue.pop();
				if (patternMatcher.match(file.getName()))
				{
					// todo
					log("filter file -> " + file.getName());
				}
			}
		}
	};
	
	private class AllFiles
	{
		public void traverse(String root)
		{
			File rootDir = new File(root);
			stack.add(rootDir);
			
			while (!stack.empty())
			{
				File dir = stack.pop();
				
				File[] files = dir.listFiles();
				if (files == null)
					continue;
				
				for (File file : files)
				{
					if (file.isDirectory())
						stack.add(file);
					
					queue.add(file); log("traverse file -> " + file);
//					h.sendEmptyMessage(0);
				}
			}
		}
		
		private Stack<File> stack = new Stack<File>();
	}

	private Context ctx;
	private PatternMatcher patternMatcher;
	
	private void log(Object x)
	{
		Log.d("FilingAdapter", x + " <- FilingAdapter");
	}
}
